package com.apestech.framework.xml.pub.core;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;


/**
 * 执行Document相关方法体
 * @author hup
 *
 */
public class XmlFile extends ElementUtil {
	
	private Document document;
	
	private String xmlHead="<?sql version=\"1.0\" encoding=\"UTF-8\"?>";
	private String xmlRootHead="<YuanYuanSoftware>";
	private String xmlRootTail="</YuanYuanSoftware>";
	private String xmlVersion="1.1710.30.0";
	private String fieldName;
	private String xmlKey="YuanYuanSoftware";
	private JSONArray nodeList;
	private JSONObject node;
	
	public void setXmlHead(String xmlHead){
		this.xmlHead=xmlHead;
	}
	
	public void setXmlRoot(String rootHead, String rootTail){
		this.xmlRootHead=rootHead;
		this.xmlRootTail=rootTail;
	}
	
	public void loadFromFile(String fieldName) throws Exception{
		this.fieldName=fieldName;
		SAXReader reader = new SAXReader();  
		try {
			document = reader.read(new File(this.fieldName));
		} catch (DocumentException e) {
			throw new Exception(getMessage("load_xml_error","读取XML失败:\r    "+e.getMessage()));
		} 
	}
	
	public void loadFromString(String xmlString) throws Exception{
		loadFromString(xmlString, true);
	}
	
	public void loadFromString(String xmlString, boolean writeHead) throws Exception{
		String sXml=xmlString.trim();
		if(!writeHead){
			if(sXml.indexOf("<")!=0) {
				writeHead=true;
			} else if(!">".equals(rightStr(sXml,1))){
				writeHead=true;
			} else {
				int len=sXml.length();
				String str="";
				for(int i=1; i<len; i++){
					String s=sXml.substring(i,i+1);
					String s1=sXml.substring(i,i+2);
					if(" ".equals(s) || ">".equals(s)){
						break;
					}
					if("/>".equals(s1)){
						writeHead=true;
						break;
					}
					str=str+s;
				}
				if(writeHead){
					String st=str;
					str="";
					for(int i=len-1; i>=0; i--){
						String s=sXml.substring(i-1,i);
						if("/".equals(s)){
							break;
						}
						str=s+str;
					}
					if(!st.equals(str)){
						writeHead=true;
					}
				}
			}
		}
		if(writeHead){
			sXml=this.xmlHead+this.xmlRootHead+sXml+this.xmlRootTail;	
		}
		try {
			document = DocumentHelper.parseText(sXml);
		} catch (DocumentException e) {
			throw new Exception(getMessage("load_xml_error","读取XML失败:\r    "+e.getMessage()));
		}		
	}
	
	public Element getRoot(){
		return document.getRootElement();
	}

}
